/*
 * 2005-12-09 lxm 创建。 
 */
package com.hd123.rumba.runtime;

import java.io.IOException;
import java.io.Serializable;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;


/**
 * @author lxm
 * 
 * 可以被序列化为XML的持久化对象基类。<br>
 * 其子类应该同时实现接口<code>IXMLSerializable</code>。
 * 
 */
public class XMLPersistent implements Serializable {

  private void writeObject(java.io.ObjectOutputStream out) throws IOException {
    try {
      if (!(this instanceof IXMLPersistent))
        throw new Exception(this.getClass().getName() + "必须实现接口" + IXMLPersistent.class.getName()
            + "。");
      IXMLPersistent self = (IXMLPersistent) this;

      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      Document doc = builder.newDocument();
      Element e = doc.createElement(self.getXMLTagName());
      self.writeToXML(doc, e);
      doc.appendChild(e);
      Transformer t = TransformerFactory.newInstance().newTransformer();
      t.transform(new DOMSource(doc), new StreamResult(out));
    } catch (Exception e) {
      throw new IOException(e.getMessage());
    }
  }

  private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException {
    try {
      if (!(this instanceof IXMLPersistent))
        throw new Exception(this.getClass().getName() + "必须实现接口" + IXMLPersistent.class.getName()
            + "。");
      IXMLPersistent self = (IXMLPersistent) this;

      DocumentBuilder builder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
      Document doc = builder.parse(in);
      NodeList nl = doc.getElementsByTagName(self.getXMLTagName());
      if (nl.getLength() == 0)
        throw new Exception("XML序列化数据中不包含" + this.getClass().getName() + "的数据(<" 
            + self.getXMLTagName() + ">)。");
      Element e = (Element) nl.item(0);
      self.readFromXML(e);
    } catch (Exception e) {
      throw new IOException(e.getMessage());
    }
  }
}
